package com.technology.education.ui.teacher.order

import android.os.Bundle
import androidx.fragment.app.Fragment
import com.angcyo.dsladapter.removeItem
import com.angcyo.dsladapter.toDslItemList
import com.technology.education.base.BaseRecyclerFragment
import com.technology.education.data.SpKeys
import com.technology.education.data.model.TeachOrderModel
import com.technology.education.dslitem.module.ItemTeacherHomeOrder
import com.technology.education.ext.notifyDialog
import com.technology.education.ext.observe
import com.technology.education.ext.setPageItems
import com.technology.education.ext.showLog
import me.hgj.jetpackmvvm.ext.parseState

/**
 * 教师订单列表
 * @param type 0全部 1进行中 2已完成 3待评价
 */
class OrderListFragment : BaseRecyclerFragment<OrderListViewModel>() {
    companion object {
        fun newInstance(type: Int): Fragment {
            val args = Bundle()
            args.putInt("type", type)
            val fragment = OrderListFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun initViews() {
        arguments?.let {
            mViewModel.type = it.getInt("type", 0)
        }
        enableSwipe()
    }

    override fun lazyLoadData() {
        loading()
    }

    override fun onResume() {
        super.onResume()
        if (!isFirst()){
            mViewModel.refresh()
        }
    }

    override fun createObserver() {
        mViewModel.result.observe(this) {
            parseState(it, onSuccess = { data ->
                hasMore(data.total)
                loadFinish()
                setUI(data.list)
            }, onError = { it ->
                loadError()
            })
        }
        observe(SpKeys.CHANGE_ORDER_STATUS_WAIT_EVALUATE,String::class.java){
            if (mViewModel.type!=2){
                //订单状态除了已完成,全部,进行中,待评价列表都进行刷新
                refreshData()
            }
        }

        mViewModel.delResult.observe(this){
            renderAdapter {
                removeItem(it)
            }
        }
    }

    private fun setUI(list: List<TeachOrderModel>) {
        renderAdapter {
            setPageItems(
                list.toDslItemList(ItemTeacherHomeOrder::class.java) {
                    itemLongClick={
                        notifyDialog(notify = "是否删除该订单?"){
                            mViewModel.deleteOrder(itemTag!!)
                        }
                        true
                    }
                },
                mViewModel.pageIndex
            )
        }
    }
}